﻿/**
 *    Copyright 2012 Yohan Courbe
 *
 *  Licensed under the Apache License, Version 2.0 (the "License") 
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *      
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

using System.Linq;
using System.Collections;
using System.Net;

namespace NetworkAnalyzer.Engines.TcpSessionTracker
{
    class TcpSessionList : IEnumerable
    {
        private readonly ArrayList _tcpSessions = new ArrayList();

        public IEnumerator GetEnumerator()
        {
            return _tcpSessions.GetEnumerator();
        }

        public void Add(TcpSession tcpSession)
        {
            _tcpSessions.Add(tcpSession);
        }

        public void Remove(TcpSession tcpSession)
        {
            _tcpSessions.Remove(tcpSession);
        }

        public int Count
        {
            get { return _tcpSessions.Count; }
        }

        public TcpSessionList()
        {

        }

        public TcpSessionList(TcpSessionList copy)
        {
            _tcpSessions = new ArrayList(copy._tcpSessions);
        }

        public TcpSession GetTcpSession(IPAddress localhost, ushort localport, IPAddress remotehost, ushort remoteport)
        {
            foreach (TcpSession tcpSession in _tcpSessions.Cast<TcpSession>().Where(tcpSession => tcpSession.MatchSession(localhost, localport, remotehost, remoteport)))
            {
                return tcpSession;
            }

            var newTcpSession = new TcpSession(localhost, localport, remotehost, remoteport);
            _tcpSessions.Add(newTcpSession);

            return newTcpSession;
        }
    }
}
